# 作者： 李泉志
# 2025年01月13日20时32分秒
# 2947029073@qq.com

"""
1.深拷贝、浅拷贝
    1. 浅拷贝
        • 浅拷贝是对于一个对象的顶层拷贝
        通俗的理解是：拷贝了引用，并没有拷贝内容（浅copy不是直接赋值）
    2. 深拷贝
        • 深拷贝是对于一个对象所有层次的拷贝(递归)
"""


def func1():  # 浅拷贝，副本变，原不变
    a = [1, 2, 3]
    b = a.copy()
    b[0] = 4
    print(a)  # [1, 2, 3]


def func2():  # 赋值变
    a = [1, 2, 3]
    b = a
    b[0] = 4
    print(a)


import copy


def use_copy():
    """
    使用copy包中的copy
    """
    c = [1, 2, 3]
    d = copy.copy(c)
    d[0] = 10
    print(c)  # [1, 2, 3]
    print(d)  # [10, 2, 3]
    print(id(c))  # 与d的id不同，说明是浅拷贝
    print(id(d))


def use_copy2():  # 浅拷贝，只拷贝第一层a、b的引用
    a = [1, 2]
    b = [3, 4]
    c = [a, b]
    d = copy.copy(c)
    print(id(c))  # 与d的id不同，说明是浅拷贝
    print(id(d))
    a[0] = 10
    print(f'c--{c}')  # [[10, 2], [3, 4]]
    print(f'd--{d}')  # [[10, 2], [3, 4]]
    print(f'id(c[0])--{id(c[0])}  id(c[1])--{id(c[1])}')
    print(f'id(d[0])--{id(d[0])}  id(d[1])--{id(d[1])}')


def use_deepcopy():
    a = [1, 2]
    b = [3, 4]
    c = [a, b]
    d = copy.deepcopy(c)
    print(id(c))  # 与d的id不同，说明是深拷贝
    print(id(d))
    a[0] = 10
    print(f'c--{c}')  # [[10, 2], [3, 4]]
    print(f'd--{d}')  # [[1, 2], [3, 4]]
    print(f'id(c[0])--{id(c[0])}  id(c[1])--{id(c[1])}')
    print(f'id(d[0])--{id(d[0])}  id(d[1])--{id(d[1])}')


class Hero:
    def __init__(self, name, hp):
        self.name = name
        self.hp = hp
        self.equipment = ['sword', 'armor']


def use_copy_hero():  # 不涉及可变类型可以浅拷贝
    old = Hero('ant', 100)
    new = copy.copy(old)
    new.hp = 80
    print(old.hp)  # 100
    new.equipment.append('ring')
    print(old.equipment)  # ['sword', 'armor', 'ring']


def use_deepcopy_hero():  # 深拷贝
    old = Hero('ant', 100)
    new = copy.deepcopy(old)
    new.hp = 80
    print(old.hp)  # 100
    new.equipment.append('ring')
    print(old.equipment)  # ['sword', 'armor']


if __name__ == '__main__':
    # func1()
    # func2()
    # use_copy()
    # use_copy2()
    # use_deepcopy()
    # use_copy_hero()
    use_deepcopy_hero()
